﻿using System.Web;

namespace Common.Util
{
    public class Network
    {
        public static string GetIpClient()
        {
            string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            //string trueIP = "";
            if (!string.IsNullOrEmpty(ip))
            {
                //string[] ipRange = ip.Split(',');
                //int le = ipRange.Length - 1;
                //trueIP = ipRange[le];
            }
            else
            {
                ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            return ip;
        }

        /// <summary>
        /// Get local ip, using for winform and webform
        /// </summary>
        /// <returns></returns>
        public static string GetLocalIp()
        {
            string ip = null;

            // Resolves a host name or IP address to an IPHostEntry instance.
            // IPHostEntry - Provides a container class for Internet host address information. 
            System.Net.IPHostEntry ipHostEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());

            // IPAddress class contains the address of a computer on an IP network. 
            foreach (System.Net.IPAddress ipAddress in ipHostEntry.AddressList)
            {
                // InterNetwork indicates that an IP version 4 address is expected 
                // when a Socket connects to an endpoint
                if (ipAddress.AddressFamily.ToString() == "InterNetwork")
                {
                    ip = ipAddress.ToString();
                }
            }
            return ip;
        }

        public static string GetPlatformClient()
        {
            string ip = HttpContext.Current.Request.UserAgent;
            if (!string.IsNullOrEmpty(ip))
            {
                if (ip.ToLower().Contains("windows nt 6.0"))
                {
                    ip = "Win Vista";
                }
                else if (ip.ToLower().Contains("windows nt 6.1"))
                {
                    ip = "Win 7";
                }
                else
                {
                    ip = HttpContext.Current.Request.Browser.Platform;
                }
            }
            else
            {
                ip = HttpContext.Current.Request.Browser.Platform;
            }
            return ip;
        }

        public static string GetBrowserClient()
        {
            string ip = HttpContext.Current.Request.UserAgent;
            if (!string.IsNullOrEmpty(ip) && ip.ToLower().Contains("chrome"))
            {
                ip = "Chrome";
            }
            else
            {
                ip = HttpContext.Current.Request.Browser.Browser;
            }
            return ip;
        }
    }
}
